package com.kwan.xframe.util;

import android.util.Log;

import com.kwan.xframe.xbyte.ByteArrayUtil;


public class XBinaryReader {

	//操作的数组
	public byte[] data;
	public int position;

	public XBinaryReader(byte[] data) {
		this.data = data;
	}

	public int readInt16() {
		int len = 2;
		//data
		byte[] tempData = ByteArrayUtil.subBytes(data, position, len);
		//Byte
		position += len;
		return  com.kwan.xframe.util.HexUtil.byte2int(tempData);
	}

	public int readInt32() {
		int len = 4;
		//data
		byte[] tempData = ByteArrayUtil.subBytes(data, position, len);
		//Byte
		position += len;
		return com.kwan.xframe.util.HexUtil.byteArrayToInt(tempData,0);

		//return ByteArrayUtil.bytes2int(tempData);
	}

	public byte readByte() {
		byte temp = data[position];
		position++;
		return temp;
	}

	public String readString() {
		Log.e("kwan","read String :"+(data.length - position));
		byte[] tempData = ByteArrayUtil.subBytes(data, position, data.length - position);
		return new String(tempData);

	}


	public String readStringEndWith0() {

		int strlen = -1;
		//int pos = (int)pack.Position;
		for (int i = position; i < data.length; i++) {
			if (data[i] == 0) {
				strlen = i - position;
				break;
			}
		}
		if (strlen == 0) {
			position++;
			return "";
		} else if (strlen > 0) {
			//	String str = Encoding.UTF8.GetString(buf, pos, strlen);
			String str = new String(ByteArrayUtil.subBytes(data, position, strlen));
			position += strlen + 1;
			return str;
		} else {
			return null;
		}
	}

	public String readStringEndWithx0() {

		int strlen = -1;
		//int pos = (int)pack.Position;
		for (int i = position; i < data.length; i++) {
			if (data[i] == '\0') {
				strlen = i - position;
				break;
			}
		}
		if (strlen == 0) {
			position++;
			return "";
		} else if (strlen > 0) {
			//	String str = Encoding.UTF8.GetString(buf, pos, strlen);
			String str = new String(ByteArrayUtil.subBytes(data, position, strlen));
			position += strlen + 1;
			return str;
		} else {
			return null;
		}
	}


}
